package com.och.mrcp.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * 语音引擎统一配置
 * 管理语音识别、语音合成及各云服务商的配置参数
 */
@Configuration
@ConfigurationProperties(prefix = "engine")
@Data
public class EngineConfig {
    
    /**
     * 默认语音服务提供商
     */
    private String defaultProvider = "aliyun";
    
    /**
     * 语音识别配置
     */
    private RecognitionConfig recognition = new RecognitionConfig();
    
    /**
     * 语音合成配置
     */
    private SynthesisConfig synthesis = new SynthesisConfig();
    
    /**
     * 阿里云配置
     */
    private AliyunConfig aliyun = new AliyunConfig();
    
    /**
     * 腾讯云配置
     */
    private TencentConfig tencent = new TencentConfig();
    
    /**
     * 语音识别配置
     */
    @Data
    public static class RecognitionConfig {
        private String language = "zh-CN";
        private boolean enablePunctuation = true;
        private boolean enableInverseText = false;
        private String audioCodec = "pcm";
        private int sampleRate = 8000;
        private int channels = 1;
        private int maxDuration = 60000; // 最大识别时长（毫秒）
        private boolean enableRealTimeRecognition = true;
        private boolean enableWordTimeOffset = false;
        private int maxAlternatives = 1;
        private double confidenceThreshold = 0.7;
        private boolean enableVad = true;
        private double vadSensitivity = 0.5;
        private long recognitionTimeout = 10000;
        private int audioAccumulationThreshold = 1600; // 200ms at 8kHz
        private long silenceTimeout = 500;
        private int maxAudioAccumulationSize = 32000; // 4 seconds at 8kHz
    }
    
    /**
     * 语音合成配置
     */
    @Data
    public static class SynthesisConfig {
        private String voice = "xiaoyun"; // 发音人
        private String language = "zh-CN"; // 语言代码
        private String format = "pcm"; // 音频格式
        private int sampleRate = 8000; // 采样率
        private int channels = 1; // 声道数
        private int speed = 0; // 语速 (-500 到 500)
        private int pitch = 0; // 音调 (-500 到 500)
        private int volume = 50; // 音量 (0 到 100)
        private String audioCodec = "pcm"; // 音频编码
        private int maxTextLength = 1000; // 最大文本长度
        private long synthesisTimeout = 30000; // 合成超时时间（毫秒）
    }
    
    /**
     * 阿里云配置
     */
    @Data
    public static class AliyunConfig {
        private String accessKeyId;
        private String accessKeySecret;
        private String appKey;
        private String region = "cn-shanghai";
        private String nlsGatewayUrl;

        // ASR 特定配置
        private AsrConfig asr = new AsrConfig();
        
        // TTS 特定配置
        private TtsConfig tts = new TtsConfig();
        
        @Data
        public static class AsrConfig {
            private String model = "generic";
            private String customizationId;
            private boolean enableDisfluency = false;
            private boolean enableSentenceDetection = true;
            private int maxSentence = 10000;
            private boolean enableWords = false;
            private String vocabularyId;
        }
        
        @Data
        public static class TtsConfig {
            private String voice = "xiaoyun";
            private String format = "pcm";
            private int sampleRate = 8000;
            private int speechRate = 0;
            private int pitchRate = 0;
            private boolean enableSubtitle = false;
        }
    }
    
    /**
     * 腾讯云配置
     */
    @Data
    public static class TencentConfig {
        private String secretId;
        private String secretKey;
        private String appId;
        private String region = "ap-beijing";
        private String endpoint;
        
        // ASR 特定配置
        private AsrConfig asr = new AsrConfig();
        
        // TTS 特定配置
        private TtsConfig tts = new TtsConfig();
        
        @Data
        public static class AsrConfig {
            private String engineModelType = "16k_zh";
            private int channelNum = 1;
            private String resTextFormat = "0";
            private String sourceType = "1";
            private boolean filterDirty = false;
            private boolean filterModal = false;
            private boolean filterPunc = false;
            private boolean convertNumMode = true;
        }
        
        @Data
        public static class TtsConfig {
            private String voiceType = "1001";
            private String sampleRate = "16000";
            private String speed = "0";
            private String volume = "0";
            private String primaryLanguage = "1";
            private String codecType = "1";
        }
    }
    
    /**
     * 根据提供商获取识别配置
     */
    public RecognitionConfig createRecognitionConfig(String provider) {
        RecognitionConfig config = new RecognitionConfig();
        
        // 设置基础配置
        config.setLanguage(recognition.getLanguage());
        config.setEnablePunctuation(recognition.isEnablePunctuation());
        config.setEnableInverseText(recognition.isEnableInverseText());
        config.setAudioCodec(recognition.getAudioCodec());
        config.setSampleRate(recognition.getSampleRate());
        config.setChannels(recognition.getChannels());
        config.setMaxDuration(recognition.getMaxDuration());
        
        // 根据提供商进行特定配置
        if ("tencent".equalsIgnoreCase(provider) && tencent.getAsr() != null) {
            // 腾讯云特定配置调整
            if ("16k_zh".equals(tencent.getAsr().getEngineModelType())) {
                config.setSampleRate(16000);
            } else if ("8k_zh".equals(tencent.getAsr().getEngineModelType())) {
                config.setSampleRate(8000);
            }
        }
        
        return config;
    }
    
    /**
     * 根据提供商获取合成配置
     */
    public SynthesisConfig createSynthesisConfig(String provider) {
        SynthesisConfig config = new SynthesisConfig();
        
        // 设置基础配置
        config.setVoice(synthesis.getVoice());
        config.setLanguage(synthesis.getLanguage());
        config.setFormat(synthesis.getFormat());
        config.setSampleRate(synthesis.getSampleRate());
        config.setChannels(synthesis.getChannels());
        config.setSpeed(synthesis.getSpeed());
        config.setPitch(synthesis.getPitch());
        config.setVolume(synthesis.getVolume());
        config.setAudioCodec(synthesis.getAudioCodec());
        
        // 根据提供商进行特定配置
        if ("aliyun".equalsIgnoreCase(provider) && aliyun.getTts() != null) {
            // 阿里云特定配置
            config.setVoice(aliyun.getTts().getVoice());
            config.setFormat(aliyun.getTts().getFormat());
            config.setSampleRate(aliyun.getTts().getSampleRate());
            config.setSpeed(aliyun.getTts().getSpeechRate());
            config.setPitch(aliyun.getTts().getPitchRate());
        } else if ("tencent".equalsIgnoreCase(provider) && tencent.getTts() != null) {
            // 腾讯云特定配置
            config.setVoice(tencent.getTts().getVoiceType());
            config.setSampleRate(Integer.parseInt(tencent.getTts().getSampleRate()));
            config.setSpeed(Integer.parseInt(tencent.getTts().getSpeed()));
            config.setVolume(Integer.parseInt(tencent.getTts().getVolume()));
        }
        
        return config;
    }
    
    /**
     * 获取提供商配置信息
     */
    public String getProviderInfo(String provider) {
        if ("aliyun".equalsIgnoreCase(provider)) {
            return String.format("Aliyun{region=%s, appKey=%s,}",
                aliyun.getRegion(), 
                aliyun.getAppKey() != null ? "***" : "null");
        } else if ("tencent".equalsIgnoreCase(provider)) {
            return String.format("Tencent{region=%s, appId=%s}",
                tencent.getRegion(), 
                tencent.getAppId() != null ? "***" : "null");
        }
        return "Unknown provider: " + provider;
    }
    
    /**
     * 验证配置完整性
     */
    public boolean isProviderConfigValid(String provider) {
        if ("aliyun".equalsIgnoreCase(provider)) {
            return aliyun.getAccessKeyId() != null && 
                   aliyun.getAccessKeySecret() != null && 
                   aliyun.getAppKey() != null;
        } else if ("tencent".equalsIgnoreCase(provider)) {
            return tencent.getSecretId() != null && 
                   tencent.getSecretKey() != null && 
                   tencent.getAppId() != null;
        }
        return false;
    }
}
